package com.sc.nft.consume;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.sc.nft.dao.DigitalCollectionDao;
import com.sc.nft.dao.UserInfoDao;
import com.sc.nft.entity.IdcardInfo;
import com.sc.nft.entity.Order;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.enums.ClassifyType;
import com.sc.nft.enums.LinkTypeEnums;
import com.sc.nft.enums.MessageTopic;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.enums.task.ActivityTaskTypeEnum;
import com.sc.nft.enums.task.TaskOrderTypeEnum;
import com.sc.nft.enums.task.TaskTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.ActivityTaskService;
import com.sc.nft.service.TaskService;
import com.sc.nft.sup.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@RocketMQMessageListener(topic = MessageTopic.FIRST_ORDER_TOPIC + "${spring.profiles.active}", consumerGroup = MessageTopic.FIRST_ORDER_TOPIC + "${spring.profiles.active}")
@Component
@Slf4j
@RequiredArgsConstructor
public class FirstOrderConsumer implements RocketMQListener<Order> {

    private final TaskService taskService;
    private final UserInfoDao userInfoDao;
    private final ActivityTaskService activityTaskService;
    private final RedisTemplate redisTemplate;
    private final DigitalCollectionDao digitalCollectionDao;

    @Override
    public void onMessage(Order order) {
        //只有藏品才会更新最新成交价
        if(order.getTypeClassify() == ClassifyType.COLLECTION){
            digitalCollectionDao.newDealSave(order.getRelationId(), order.getProductPrice().divide(Convert.toBigDecimal(order.getCount())));
        }
        String key = RedisKeyEnum.FIRST_ACTIVITY_TASK_LOCK.getKey() + order.getOrderNo();
        Long increment = redisTemplate.opsForValue().increment(key);
        log.info("首发订单任务{},第{}次进入",order.getOrderNo(),increment);
        redisTemplate.expire(key,180,TimeUnit.MINUTES);
        if(increment.longValue()>1L){
            return;
        }
        try {
            UserInfo userInfo = userInfoDao.getById(order.getUserId());
            taskService.finishTask(userInfo, TaskOrderTypeEnum.FIRST, TaskTypeEnum.NEW_BUY, order.getId(), order.getRelationId(), order.getProductPrice());
            taskService.finishTask(userInfo, TaskOrderTypeEnum.FIRST, TaskTypeEnum.BUY_APPOINT, order.getId(), order.getRelationId(), order.getProductPrice());
            taskService.finishTask(userInfo, TaskOrderTypeEnum.FIRST, TaskTypeEnum.TOTAL_SPEND, order.getId(), order.getRelationId(), order.getProductPrice());

            UserInfo inviteUser = userInfoDao.getById(userInfo.getRecommendUserId());
            if (ObjectUtil.isNull(inviteUser)) {
                return;
            }
            log.info("星球任务完成：{}",order.getOrderNo());

            taskService.finishTask(inviteUser, TaskOrderTypeEnum.FIRST, TaskTypeEnum.DAO, order.getId(), order.getRelationId(), order.getProductPrice());
            if (order.getTypeClassify() == ClassifyType.COLLECTION) {
                activityTaskService.finishTask(order.getRelationId(), order.getUserId(), order.getCount(), order.getProductPrice(), ActivityTaskTypeEnum.BUY_APPOINT, LinkTypeEnums.ORDER, order.getId(), false);
                activityTaskService.finishTask(order.getRelationId(), order.getUserId(), order.getCount(), order.getProductPrice(), ActivityTaskTypeEnum.TOTAL_BUY, LinkTypeEnums.ORDER, order.getId(), false);
                activityTaskService.finishTask(order.getRelationId(), order.getUserId(), order.getCount(), order.getProductPrice(), ActivityTaskTypeEnum.TOTAL_SPEND, LinkTypeEnums.ORDER, order.getId(), false);
            }
            log.info("活动任务完成：{}",order.getOrderNo());

        } catch (Exception e) {
            log.error("任务奖励发放失败", e);
        }
    }
}
